import authApi from "@/api/auth"
import Cookies from "js-cookie"
import Vue from "vue"
import {Vue2Storage} from "vue2-storage";

const SessionKey = "PHPSESSID"
Vue.use(Vue2Storage, {
	prefix: "app_",
	driver: "session",
	ttl: 60 * 60 * 24 * 1000 // 24 часа
})

const user = {
	state: {
		id: null,
		name: "",
		menus: [],
		routers: [],
		version: "",
		sysTitle: "",
		token: "",
    auths:[],
	},
	getters: {
		hasUserInfo: state => {
			return state.id != null
		},
		hasSession: state => {
			return !!Vue.$storage.get("token");
		},
    getToken: state => {
      return Vue.$storage.get("token");
    },
	},
	mutations: {
		SET_USERID(state, id) {
			state.id = id
		},
		SET_NAME(state, name) {
			state.name = name
		},
		SET_TOKEN(state, token) {
			state.token = token
		},
		SET_EMPLOYEE(state, employee) {
			state.employee = employee
		},
		SET_MENUS(state, menus) {
			state.menus = menus
		},
    SET_AUTHS(state, auths) {
      state.auths = auths
    },
		SET_ROUTERS(state, routers) {
			state.routers = routers
			console.log(state);
		},
		SET_VERSION(state, version) {
			state.version = version
		}
	},
	actions: {
		login({commit}, user) {
			return new Promise((resolve, reject) => {
				authApi.login(user.username, user.password).then(res => {
					commit("SET_TOKEN", res.data.token)
					resolve(res)
				}).catch(error => reject(error))
			})
		},
		getUserInfo({commit, dispatch}) {
			return new Promise((resolve, reject) => {
				authApi.getUserInfo().then(res => {
					commit("SET_USERID", res.data.userid)
					commit("SET_NAME", res.data.username)
					commit("SET_MENUS", res.data.menuList)
					commit("SET_AUTHS", res.data.authList)
					resolve(res)
				}).catch(error => {
					// dispatch("logout")
					reject(error)
				})
			})
		},
		logout({commit}) {
			Cookies.remove(SessionKey)
			window.location.reload()
		},
		setMenus({commit}, menus) {
			commit("SET_MENUS", menus)
		},
		setRouters({commit}, routers) {
			console.log(routers);
			commit("SET_ROUTERS", routers)
		},
		hasPath({state, commit}, path) {
			return state.menus.some((item, index) => {
				if (item.path == path) {
					console.log("hehe")
					return true
				} else {
					return false
				}
			})
		}
	}
}
export default user
